/**
 * Created by bian on 16-11-16.
 */
var fs = require("fs");
var path = require("path");
const PassThrough = require('stream').PassThrough;

module.exports = (router) => {
    router.get("/video/:filename", function *() {
        var ctx = this;
        var res = ctx.response;
        var req = ctx.request;
        var filename = ctx.params.filename;

        var file = path.resolve(__dirname, `../public/p_dist/upload/${filename}`);
        try {
            var stats = fs.statSync(file);

            var range = req.headers.range;
            if (!range) {
                // 416 Wrong range
                res.status = 416;
                return;
            }
            var positions = range.replace(/bytes=/, "").split("-");
            var start = parseInt(positions[0], 10);
            var total = stats.size;
            var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
            var chunksize = (end - start) + 1;

            res.status = 206;
            res.set({
                "Content-Range": "bytes " + start + "-" + end + "/" + total,
                "Accept-Ranges": "bytes",
                "Content-Length": chunksize,
                "Content-Type": "video/mp4"
            });

            var stream = fs.createReadStream(file, {start: start, end: end});
            res.body = stream;

        } catch (err) {
            if (err) {
                if (err.code === 'ENOENT') {
                    // 404 Error if file not found
                    res.status = 404;
                }
                res.body = err;
            }
        }
    });
};